package com.example.gymnasiumsystem.servlet;
import com.example.gymnasiumsystem.dao.UserInfoDAO;
import com.example.gymnasiumsystem.enity.UserInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserInfoDAO userInfoDAO = new UserInfoDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/admin/register.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  // 设置请求字符编码为UTF-8
        response.setContentType("text/html;charset=UTF-8");  // 设置响应字符编码为UTF-8
        String studentNumber = request.getParameter("studentNumber");
        String password = request.getParameter("password");
        String userName = request.getParameter("username");
        // 验证图形验证码
        String captcha = request.getParameter("captcha");
        HttpSession session = request.getSession();
        String sessionCaptcha = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
        if (captcha == null &&!captcha.equals(sessionCaptcha)) {
            request.setAttribute("errorMessage", "验证码错误");
            request.getRequestDispatcher("admin/register.jsp").forward(request, response);
            return;
        }

        // 创建并保存学生信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(userName);
        userInfo.setPassword(password);
        userInfo.setAdmin(0);
        userInfoDAO.addUser(userInfo);
        response.sendRedirect("/gym/admin/login.jsp"); // 注册成功后跳转到登录页面
    }
}
